import {
    closestCenter,
    DndContext,
    DragEndEvent,
    MouseSensor,
    useSensor,
    useSensors
} from "@dnd-kit/core";
import {SortableContext, verticalListSortingStrategy} from "@dnd-kit/sortable";
import {ReactElement} from "react";

type PropsType = {
    children: ReactElement | ReactElement[]
    items: Array<{ id: string, [key: string]: any }>
    onDragEnd: (oldIndex: number, newIndex: number) => void
}
export const SortableContainer = (props: PropsType) => {
    const {children, items, onDragEnd} = props
    const sensors = useSensors(
        useSensor(MouseSensor, {activationConstraint: {distance: 8}})
    )

    function handlerDragEnd(event: DragEndEvent) {
        const {active, over} = event;
        if (over == null) return
        if (active.id !== over.id) {
            const oldIndex = items.findIndex(item => item.id === active.id)
            const newIndex = items.findIndex(item => item.id === over.id)
            onDragEnd(oldIndex, newIndex)
        }
    }

    return (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handlerDragEnd}>
            <SortableContext items={items} strategy={verticalListSortingStrategy}>
                {children}
            </SortableContext>
        </DndContext>
    );
};